<template>
  <div class="messages-page">
    <!-- 顶部导航栏 -->
    <el-header>
      <el-menu mode="horizontal" background-color="#545c64" text-color="#fff" active-text-color="#ffd04b" router>
        <div class="logo">
          <i class="el-icon-chat-line-round"></i>
          校园二手书交易平台
        </div>
        <el-menu-item index="/home">首页</el-menu-item>
        <el-menu-item index="/market">书籍市场</el-menu-item>
        <el-menu-item index="/my-posts">我的发布</el-menu-item>
        <el-menu-item index="/messages">消息中心</el-menu-item>
      </el-menu>
    </el-header>

    <div class="messages-container">
      <el-container>
        <el-aside width="280px" class="contacts-aside">
          <div class="search-box">
            <el-input
              placeholder="搜索联系人"
              v-model="searchContact"
              prefix-icon="el-icon-search"
              clearable
            ></el-input>
          </div>
          
          <div class="contact-list">
            <div 
              v-for="contact in contacts" 
              :key="contact.id" 
              class="contact-item"
              :class="{ 'active': currentContact && currentContact.id === contact.id }"
              @click="selectContact(contact)"
            >
              <div class="contact-info">
                <el-avatar :size="40" class="contact-avatar">{{ contact.name.charAt(0) }}</el-avatar>
                <div class="contact-detail">
                  <div class="contact-name">{{ contact.name }}</div>
                  <div class="last-message">{{ contact.lastMessage }}</div>
                </div>
              </div>
              <el-badge :value="contact.unread" :hidden="!contact.unread"/>
            </div>
          </div>
        </el-aside>

        <el-main class="chat-main">
          <div v-if="currentContact" class="chat-container">
            <div class="chat-header">
              <h3>{{ currentContact.name }}</h3>
            </div>

            <div class="chat-messages" ref="messageContainer">
              <div class="messages-wrapper">
                <div v-for="msg in messages" :key="msg.id" :class="['message-wrapper', msg.type]">
                  <div class="message-content">
                    <div class="message-time">{{ msg.time }}</div>
                    {{ msg.content }}
                  </div>
                </div>
              </div>
            </div>

            <div class="chat-input">
              <el-input
                type="textarea"
                v-model="newMessage"
                :rows="3"
                placeholder="输入消息..."
                @keyup.enter.native="sendMessage"
              ></el-input>
              <div class="input-actions">
                <el-button type="primary" @click="sendMessage">发送</el-button>
              </div>
            </div>
          </div>
          <div v-else class="no-chat-selected">
            <el-empty description="选择一个联系人开始聊天"></el-empty>
          </div>
        </el-main>
      </el-container>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'MessagesPage',
  data() {
    return {
      searchContact: '',
      contacts: [],
      currentContact: null,
      messages: [],
      newMessage: '',
      queryParams: {
        currentPage: 1,
        pageSize: 10,
        status: null
      }
    }
  },
  methods: {
    // 获取联系人列表
    async getContacts() {
      try {
        const res = await request.get('/api/messages/contacts')
        if (res.data.code === 1) {
          this.contacts = res.data.data
        } else {
          this.$message.error(res.data.msg || '获取联系人列表失败')
        }
      } catch (error) {
        this.$message.error('获取联系人列表失败')
      }
    },

    // 获取消息列表
    async getMessageList() {
      if (!this.currentContact) return
      
      try {
        const res = await request.get('/api/messages/list', { 
          params: {
            currentPage: this.queryParams.currentPage,
            pageSize: this.queryParams.pageSize,
            status: this.queryParams.status,
            contactId: this.currentContact.id
          }
        })
        if (res.data.code === 1) {
          // 将消息按时间顺序显示
          this.messages = res.data.data.records.map(msg => ({
            id: msg.id,
            content: msg.content,
            type: msg.senderId === this.currentContact.id ? 'received' : 'sent',
            time: new Date(msg.createTime).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
          }))
          // 滚动到底部
          this.$nextTick(() => {
            this.scrollToBottom()
          })
        } else {
          this.$message.error(res.data.msg || '获取消息列表失败')
        }
      } catch (error) {
        this.$message.error('获取消息列表失败')
      }
    },

    // 发送消息
    async sendMessage() {
      if (!this.newMessage.trim() || !this.currentContact) {
        return
      }

      try {
        const message = {
          receiverId: this.currentContact.id,
          content: this.newMessage
        }
        const res = await request.post('/api/messages/send', message)
        if (res.data.code === 1) {
          // 发送成功后重新获取消息列表
          await this.getMessageList()
          this.newMessage = ''
          // 刷新联系人列表以更新最后一条消息
          this.getContacts()
        } else {
          this.$message.error(res.data.msg || '发送消息失败')
        }
      } catch (error) {
        this.$message.error('发送消息失败')
      }
    },

    // 标记消息为已读
    async markAsRead(messageId) {
      try {
        const res = await request.put(`/api/messages/read/${messageId}`)
        if (res.data.code === 1) {
          const message = this.messages.find(m => m.id === messageId)
          if (message) {
            message.status = 1
          }
        }
      } catch (error) {
        console.error('标记消息已读失败:', error)
      }
    },

    // 选择联系人
    async selectContact(contact) {
      this.currentContact = contact
      contact.unread = 0
      await this.getMessageList()
    },

    // 滚动到底部
    scrollToBottom() {
      const container = this.$refs.messageContainer
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    }
  },
  created() {
    this.getContacts()
  },
  watch: {
    messages: {
      handler() {
        this.scrollToBottom()
      },
      deep: true
    }
  }
}
</script>

<style scoped>
.messages-page {
  min-height: 100vh;
  background-color: #f0f2f5;
}

.el-header {
  padding: 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);
}

.logo {
  float: left;
  line-height: 60px;
  margin: 0 20px;
  color: #fff;
  font-size: 20px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.logo i {
  margin-right: 10px;
  font-size: 24px;
}

.messages-container {
  height: calc(100vh - 60px);
  padding: 20px;
}

.contacts-aside {
  background: #fff;
  border-radius: 12px;
  margin-right: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.search-box {
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.contact-list {
  overflow-y: auto;
  height: calc(100% - 80px);
}

.contact-item {
  padding: 15px 20px;
  border-radius: 8px;
  margin: 5px 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  transition: all 0.3s ease;
}

.contact-item:hover {
  background-color: #f5f7fa;
  transform: translateX(5px);
}

.contact-item.active {
  background-color: #ecf5ff;
  border-left: 4px solid #409EFF;
}

.contact-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.contact-avatar {
  background: linear-gradient(135deg, #409EFF, #36cfc9);
  color: #fff;
  border: 2px solid #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.contact-detail {
  flex: 1;
  overflow: hidden;
}

.contact-name {
  font-size: 14px;
  color: #303133;
  margin-bottom: 4px;
  font-weight: 500;
}

.last-message {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chat-main {
  background: #fff;
  border-radius: 12px;
  padding: 0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  height: calc(100vh - 100px);
}

.chat-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
  background: linear-gradient(to right, #f5f7fa, #fff);
  border-radius: 12px 12px 0 0;
}

.chat-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
  font-weight: 600;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #f9f9f9;
  position: relative;
}

.messages-wrapper {
  display: flex;
  flex-direction: column;
  min-height: 100%;
  justify-content: flex-end;
}

.message-wrapper {
  margin: 10px 0;
  display: flex;
  flex-direction: column;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message-content {
  padding: 12px 16px;
  border-radius: 12px;
  max-width: 70%;
  word-break: break-all;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.received {
  align-items: flex-start;
}

.received .message-content {
  background: linear-gradient(135deg, #fff, #f8f9fa);
  margin-left: 10px;
}

.sent {
  align-items: flex-end;
}

.sent .message-content {
  background: linear-gradient(135deg, #409EFF, #36cfc9);
  color: #fff;
  margin-right: 10px;
}

.sent .message-time {
  color: #fff;
  opacity: 0.8;
}

.chat-input {
  padding: 20px;
  border-top: 1px solid #eee;
  background: #fff;
  border-radius: 0 0 12px 12px;
}

.input-actions {
  margin-top: 10px;
  text-align: right;
}

.input-actions .el-button {
  padding: 12px 24px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.input-actions .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.no-chat-selected {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 16px;
}

::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

::-webkit-scrollbar-track {
  background: #f5f5f5;
  border-radius: 3px;
}
</style>